<%--
  Created by IntelliJ IDEA.
  User: DongZhengWei
  Date: 2018/8/24
  Time: 16:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>

<div id="page-content">

	<div class="panel">
		<div class="panel-heading">
			<h3 class="panel-title">部门信息</h3>
		</div>
		<div class="panel-body">
			<div class="col-md-3">
				<ul id="tree_department" class="ztree"></ul>
			</div>
			<div class="col-md-9">
				<table id="duty_table" cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered"></table>
			</div>
		</div>
	</div>

</div>

<script>

	$(function(){
        init_tree_department();
	});

	function init_tree_department(){

	    var setting = {
	        async : {
	            enable : true,
				url : "<%=path%>/main/department/tree",
				autoParam : ['id'],
				type : "GET",
				dataType : "json",
                contentType : "application/json"
			},
			callback : {
                onAsyncError : deptOnAsyncError,
                onAsyncSuccess : deptOnAsyncSuccess,
                beforeEditName : zTreeBeforeEditName,
                beforeRemove : zTreeBeforeRemove,
                onClick: zTreeOnClick
			},
            data : {
                simpleData : {
                    enable : true,
                    idKey : 'id',
                    pIdKey : 'pId',
                    rootPId : ''
                }
            },
			edit : {
				enable : true,
                removeTitle: '删除',
                renameTitle: '编辑',
                showRemoveBtn: setRemoveBtn,
                showRenameBtn: setRenameBtn
			},
			view : {
	            addHoverDom : addHoverDom,
                removeHoverDom : removeHoverDom,
                autoCancelSelected: true,
                dblClickExpand: true,
                selectedMulti: false
			}
		};

        $.fn.zTree.init($('#tree_department'), setting);
	}

	//异步加载出现异常错误
    function deptOnAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
	    console.log(XMLHttpRequest);
    }

	//异步加载成功
	function deptOnAsyncSuccess(event, treeId, treeNode, msg){
	    var zTree = $.fn.zTree.getZTreeObj(treeId);
	    if(treeNode){
	        if(treeNode.id === "0"){
                var nodes = treeNode.children;
                zTree.selectNode(nodes[0]);
                init_dataTables_duty(nodes[0].id);
			}
		}else{
            var rootNode = zTree.getNodes()[0];
            if (rootNode.isParent) {
                zTree.expandNode(rootNode, true, true, true);
            }
		}
	}

	//设置顶级没有删除按钮
	function setRemoveBtn(treeId, treeNode){
	    return treeNode.id !== "0";
	}

    //设置顶级没有编辑按钮
    function setRenameBtn(treeId, treeNode) {
        return (treeNode.id !== '0');
    }

    //节点后面的添加按钮
    function addHoverDom(treeId, treeNode) {
        var sObj = $('#' + treeNode.tId + '_span');
        if (treeNode.editNameFlag || $('#addBtn_'+treeNode.id).length>0) return;
        var addStr = '<span class="button add" id="addBtn_' + treeNode.id + '" title="新增" onfocus="this.blur();"></span>';
        sObj.after(addStr);
        var btn = $('#addBtn_'+treeNode.id);
        if (btn) btn.bind('click', function(){
            add_department(treeNode.id);
            return false;
        });
    }

    //鼠标移除节点时，隐藏自定义按钮
	function removeHoverDom(treeId, treeNode){
        $('#addBtn_'+treeNode.id).unbind().remove();
	}

	//点击添加按钮
	function add_department(departmentId){
		var url = "<%=path%>/main/department/input?parentId=" + departmentId;
		__open_dialog_form("新增部门", url, function(dialogRef){
		    var callback = function(data){
		        if(data){
		            dialogRef.close();
                    refresh_department(data.parentId);
				}else{
		            dialogRef.enableButtons();
				}
			};
		    if(!fn_department_input_save(callback)){
                dialogRef.enableButtons();
			}
		});
	}

	//点击编辑按钮
	function zTreeBeforeEditName(treeId, treeNode){
        var url = "<%=path%>/main/department/input?keyId=" + treeNode.id;
        __open_dialog_form("编辑部门", url, function(dialogRef){
            var callback = function(data){
                if(data){
                    dialogRef.close();
                    refresh_department(data.parentId);
				}else{
                    dialogRef.enableButtons();
				}
			};
            if(!fn_department_input_save(callback)){
                dialogRef.enableButtons();
			}
		});
        return false;
	}

	//点击删除按钮
	function zTreeBeforeRemove(treeId, treeNode){
	    var id = treeNode.id;
	    if(id){
	        __confirm_dialog("提示","确定要删除此部门吗？", function(){
                var url = "<%=path%>/main/department/delete";
                __ajax_post(url,  {keyId : id}, function(data){
                    if(data.state==1){
                        __toastr_success(data.message);
                        refresh_department(0);
					}else{
                        __toastr_error(data.message);
					}
				})
			});
		}else{
	        __toastr_error("请选中一个部门");
		}
	    return false;
	}

	//刷新数据
	function refresh_department(departmentId){
		var zTree = $.fn.zTree.getZTreeObj("tree_department");
		if(departmentId){
		    var node = zTree.getNodeByParam("id", departmentId, null);
		    if(!node.isParent){
		        node.parent = true;
		        zTree.updateNode(node);
			}
			zTree.reAsyncChildNodes(node, "refresh");
		}else{
            zTree.reAsyncChildNodes(null, "refresh");
		}
	}

	//选中一个部门
	function zTreeOnClick(event, treeId, treeNode, clickFlag){
	    var id = treeNode.id;
	    if(id && id!="0"){
            $("#duty_table").DataTable().ajax.url("<%=path%>/main/duty/list_department?departmentId=" + id).load();
		}
	}

	function init_dataTables_duty(departmentId){
	    var columns = [
            {targets : 0, data : "id", title : "id", visible : false, orderable : false, searchable : false},
            {targets : 1, data : "userName", title : "成员", visible : true, orderable : true, searchable : true},
            {targets : 2, data : "postName", title : "所在岗位", visible : true, orderable : true, searchable : true},
            {targets : 3, data : "isLeader", title : "", visible : false, orderable : false, searchable : false},
		    {targets : 4, title : "操作", visible : true, orderable : false, searchable : false, render : actRender}
	    ];
	    __init_dataTables("duty_table","<%=path%>/main/duty/list_department?departmentId=" + departmentId,columns,[],false,true);
	}

    function actRender(data, type, row, meta){
        var dutyId = row.id;
        var dutyState = row.isLeader;
        if(dutyState == "1"){
            data = '<button class="btn btn-danger btn-xs" onclick="fn_depart_lead(\'' + dutyId + '\');"><i class="fa fa-pencil-square-o"> </i>撤销负责人身份</button> ';
        }else{
            data = '<button class="btn btn-warning btn-xs" onclick="fn_depart_lead(\'' + dutyId + '\');"><i class="fa fa-pencil-square-o"> </i>设为部门负责人</button> ';
        }
        return data;
    }

    //设置部门负责人
	function fn_depart_lead(dutyId){
        var treeObj = $.fn.zTree.getZTreeObj("tree_department");
        var nodes = treeObj.getSelectedNodes();
        if(nodes && nodes[0].id){
            var url = "<%=path%>/main/department/setLeader";
            __ajax_post(url, {dutyId : dutyId, departmentId : nodes[0].id}, function(data) {
                __toastr(data);
                $("#duty_table").DataTable().ajax.reload();
            });
        }else{
            __toastr_error("未获取到部门信息");
        }


	}

</script>